<?php

namespace App\Http\Controllers;

use App\Services\EnvConfigService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Validator;

class WebSocketConfigController extends Controller
{
    protected $envConfigService;

    public function __construct(EnvConfigService $envConfigService)
    {
        $this->middleware('auth.api');
        $this->envConfigService = $envConfigService;
    }

    /**
     * 获取 WebSocket 配置
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        try {
            $config = $this->envConfigService->getWebSocketConfig();
            
            // 转换为前端需要的格式
            $data = [
                'enabled' => $config['WEBSOCKET_ENABLED'] === 'true' || $config['WEBSOCKET_ENABLED'] === '1',
                'base_url' => $config['WEBSOCKET_BASE_URL'],
                'ws_url' => $config['WEBSOCKET_WS_URL'],
                'timeout' => (int) $config['WEBSOCKET_TIMEOUT'],
            ];

            return $this->success($data, '获取成功');
        } catch (\Exception $e) {
            return $this->error('获取配置失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 更新 WebSocket 配置
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'enabled' => 'nullable|boolean',
            'base_url' => 'nullable|string|url',
            'ws_url' => 'nullable|string',
            'timeout' => 'nullable|integer|min:1|max:300',
        ], [
            'base_url.url' => 'HTTP API 地址格式不正确',
            'ws_url.string' => 'WebSocket 地址格式不正确',
            'timeout.integer' => '超时时间必须是整数',
            'timeout.min' => '超时时间不能小于1秒',
            'timeout.max' => '超时时间不能大于300秒',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator);
        }

        try {
            $data = $request->only(['enabled', 'base_url', 'ws_url', 'timeout']);
            
            // 转换为 .env 格式
            $config = [];
            if (isset($data['enabled'])) {
                $config['WEBSOCKET_ENABLED'] = $data['enabled'];
            }
            if (isset($data['base_url'])) {
                $config['WEBSOCKET_BASE_URL'] = $data['base_url'];
            }
            if (isset($data['ws_url'])) {
                $config['WEBSOCKET_WS_URL'] = $data['ws_url'];
            }
            if (isset($data['timeout'])) {
                $config['WEBSOCKET_TIMEOUT'] = $data['timeout'];
            }

            $updated = $this->envConfigService->updateWebSocketConfig($config);

            if ($updated) {
                // 清除配置缓存
                Artisan::call('config:clear');
                
                return $this->success(null, '配置更新成功，配置缓存已清除');
            } else {
                return $this->error('配置更新失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('配置更新失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 刷新配置缓存
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        try {
            // 清除配置缓存，让系统重新读取 .env 文件
            Artisan::call('config:clear');
            
            return $this->success(null, '配置缓存已清除，新配置已生效');
        } catch (\Exception $e) {
            return $this->error('刷新配置缓存失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 清除配置缓存
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearCache()
    {
        try {
            Artisan::call('config:clear');
            
            return $this->success(null, '配置缓存已清除');
        } catch (\Exception $e) {
            return $this->error('清除配置缓存失败：' . $e->getMessage(), 500);
        }
    }
}

